# -*- coding: utf-8 -*-

import json
import logging

from django.views.decorators.http import require_POST, require_GET

from common.chase import db as chase_db
from common.chase import handler as chase_handler
from common.mch import db as mch_db
from common.utils.api import check_params
from common.utils.api import token_required
from common.utils.decorator import response_wrapper, safe_wrapper
from common.utils.tz import utc_to_local_str

_LOGGER = logging.getLogger(__name__)


@require_GET
@token_required
@response_wrapper
def get_order_list(req):
    query_dct = req.GET.dict()
    mch_dct = mch_db.get_mch_dct()
    items, total_count, total_amount = chase_db.list_order(query_dct)
    resp_items = []
    for item in items:
        data = item.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        data['mch_id'] = mch_dct[data['mch_id']]
        data['chase_origin_id'] = str(data['chase_origin_id'])
        data['id'] = str(data['id'])
        resp_items.append(data)
    return {
        'list': resp_items,
        'page': query_dct.get('$page', 1),
        'total_amount': str(total_amount) if total_amount else '0',
        'size': len(resp_items),
        'total_count': total_count
    }


@require_POST
@response_wrapper
@token_required
@safe_wrapper
def create_chase_order(req):
    """
    {"chase_type": 1, "amount": "1", "desc": "test", "user_id": 181538,
     "mch_id": "6001015", "chase_origin_type": 0, "chase_origin_id": 395178,
     "service": "alipay", "channel_id": "421"}

    :param
    :chase_type 0: 加分, 1: 减分
    :chase_origin_type 0: 充值, 1: 提现
    :chase_origin_id 关连原本订单
    """

    params = json.loads(req.body)
    check_params(params, ['service', 'amount', 'mch_id',
                          'desc', 'user_id', 'channel_id'])

    _LOGGER.info('create chase request: %s' % params)
    params['operator'] = req.user.nickname
    params['operator_id'] = req.user.id
    chase_origin_type = params['chase_origin_type']
    chase_origin_id = params.get('chase_origin_id', None)

    # 根据 mch_id 调用不同商户api
    chase_order = chase_handler.create_chase_charge(params)

    return {
        'order_id': chase_order.id,
        'order_status': chase_order.status
    }


@require_POST
@response_wrapper
@token_required
def review_order(req, order_id):
    params = json.loads(req.body)
    review_type = params['review_type']
    order_id = int(order_id)
    # chase_order = chase_db.get_order(order_id)
    # reason = chase_order.desc
    # order_db.set_pay_success(order_id, reason)
    # async_job.notify_mch.delay(order_id)
    chase_db.update_order(order_id, review_type)
    return {'id': order_id, 'result': 'success'}
